package main

import (
	"fmt"
	"log"
	"myapp/config"
	"myapp/router"
	"os"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var db *gorm.DB

func init() {
	logFile, err := os.OpenFile("./xx.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open log file failed, err:", err)
		return
	}
	log.SetOutput(logFile)
	log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)

	config.Init()

	db, err = gorm.Open(mysql.Open(config.Conf.MysqlDSN), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}
}

func goStart() {
	// 自动迁移
	/*err := db.AutoMigrate(
		&model.User{},
		&model.Role{},
		&model.Permission{},
	)
	if err != nil {
		log.Fatal("自动迁移失败:", err)
	}*/

	r := router.SetupRouter(db)

	log.Println("启动服务，端口:", config.Conf.AppPort)
	err := r.Run(":" + config.Conf.AppPort)
	if err != nil {
		log.Fatal("启动失败:", err)
	}
}

func main() {
	Execute()
}
